<template>
    <view class="add-address-page">
        <view class="form-item">
            <view class="label">收货人</view>
            <input class="input" placeholder="请填写收货人姓名" v-model="receiverName"
                @input="handleInputChange('receiverName')" />
        </view>

        <view class="form-item">
            <view class="label">手机号</view>
            <input class="input" placeholder="请填写收货人手机号" v-model="phoneNumber" type="number"
                @input="handleInputChange('phoneNumber')" maxlength="11" />
        </view>

        <view class="address-section">
            <view class="tab-bar">
                <view class="tab" :class="{ active: currentTab === 'map' }" @click="switchTab('map')">
                    地图选址
                </view>
                <view class="tab" :class="{ active: currentTab === 'region' }" @click="switchTab('region')"
                    @click1="showRegionPopup = true">
                    地区选址（含港澳台及海外）
                </view>
                <!-- 底部弹出的地区选择弹窗 -->
                <uni-popup v-model="showRegionPopup" type="bottom" :height="700rpx">
                    <view class="region-popup">
                        <!-- 弹窗标题栏 -->
                        <view class="popup-header">
                            <text class="close-btn" @click="showRegionPopup = false">取消</text>
                            <text class="title">所在地区</text>
                            <text class="confirm-btn" @click="confirmRegion">确定</text>
                        </view>

                        <!-- 地区选择内容（根据你的截图实现） -->
                        <view class="region-content">
                            <!-- 切换标签：中国大陆/港澳台及海外 -->
                            <view class="region-tabs">
                                <text :class="{ active: currentTab === 'mainland' }"
                                    @click="currentTab = 'mainland'">中国大陆</text>
                                <text :class="{ active: currentTab === 'overseas' }"
                                    @click="currentTab = 'overseas'">港澳台及海外</text>
                            </view>

                            <!-- 地区列表（示例：北京市-昌平区-崔村镇） -->
                            <view class="region-list">
                                <view class="region-item">北京</view>
                                <view class="region-item">昌平区</view>
                                <view class="region-item active">崔村镇</view>
                                <!-- 其他地区选项... -->
                            </view>
                        </view>
                    </view>
                </uni-popup>

            </view>

            <view class="address-item">
                <view class="label">地址</view>
                <view class="page-body">
                    <view class="page-section page-section-gap">
                        <map style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude"
                            :markers="covers">
                        </map>
                    </view>
                </view>
                <view class="address-select">
                    <view class="current-location">
                        {{ currentLocation.name || '未选择地址' }}
                        <view class="location-desc" v-if="currentLocation.area">
                            {{ currentLocation.area }}
                        </view>
                    </view>
                    <button class="use-btn" @click="chooseLocation">使用</button>
                </view>
            </view>
        </view>

        <view class="form-item">
            <view class="label">门牌号</view>
            <input class="input" placeholder="例：6栋201室" v-model="houseNumber"
                @input="handleInputChange('houseNumber')" />
        </view>

        <view class="paste-board" @click="togglePasteBoard">
            地址粘贴板 {{ showPasteBoard ? '▲' : '▼' }}
        </view>
        <view v-if="showPasteBoard" class="paste-content">
            <view class="paste-item" v-for="(item, index) in pasteHistory" :key="index" @click="usePasteAddress(item)">
                {{ item.name }} {{ item.phone }} {{ item.fullAddress }}
            </view>
        </view>

        <view class="form-item">
            <view class="label">设为默认地址</view>
            <switch :checked="isDefault" @change="toggleDefault" />
            <view class="tip">下单时会优先使用该地址</view>
        </view>

        <view class="form-item">
            <view class="label">标签</view>
            <view class="tag-group">
                <view class="tag" :class="{ active: selectedTag === '学校' }" @click="selectTag('学校')">
                    学校
                </view>
                <view class="tag" :class="{ active: selectedTag === '家' }" @click="selectTag('家')">
                    家
                </view>
                <view class="tag" :class="{ active: selectedTag === '公司' }" @click="selectTag('公司')">
                    公司
                </view>
                <view class="tag" :class="{ active: selectedTag === '购物' }" @click="selectTag('购物')">
                    购物
                </view>
                <view class="tag" :class="{ active: selectedTag === '秒送/外卖' }" @click="selectTag('秒送/外卖')">
                    秒送/外卖
                </view>
                <view class="tag custom" @click="selectTag('自定义')">
                    自定义
                </view>
            </view>
        </view>

        <button class="confirm-btn" :disabled="!canSubmit" @click="submitAddress">
            确认
        </button>
    </view>
</template>

<script>
export default {
    data() {
        return {
            receiverName: '',
            phoneNumber: '',
            houseNumber: '',
            isDefault: false,
            selectedTag: '',
            currentTab: 'map', // 默认地图选址
            currentLocation: {
                name: '智慧谷-C2',
                area: '北京海淀区',
                longitude: '', // 经度
                latitude: ''  // 纬度
            },
            showPasteBoard: false,
            pasteHistory: [], // 地址粘贴板历史
            formErrors: {}, // 表单错误信息
            id: 0, // 使用 marker点击事件 需要填写id
            title: 'map',
            latitude: 39.909,
            longitude: 116.39742,
            covers: [{
                latitude: 39.909,
                longitude: 116.39742,
                iconPath: '../../../static/location.png'
            }, {
                latitude: 39.90,
                longitude: 116.39,
                iconPath: '../../../static/location.png'
            }],
            showRegionPopup: false, // 控制弹窗显示/隐藏
            currentTab: 'mainland', // 当前选中的标签（中国大陆/港澳台及海外）
            selectedRegion: ['北京', '昌平区', '崔村镇'] // 选中的地区
        };
    },
    computed: {
        // 验证表单是否可以提交
        canSubmit() {
            return this.receiverName &&
                this.phoneNumber &&
                /^1[3-9]\d{9}$/.test(this.phoneNumber) &&
                this.currentLocation.name &&
                this.houseNumber;
        }
    },
    onLoad() {
        // 页面加载时获取地址粘贴板历史
        this.getPasteHistory();
        // 如果需要自动定位，可以在这里调用定位接口
    },
    methods: {
        // 切换标签页
        switchTab(tabType) {
            this.currentTab = tabType;
            // 如果切换到地区选址，可以在这里加载地区数据
            if (tabType === 'region') {
                this.loadRegionData();
            }
        },

        // 处理输入框变化
        handleInputChange(field) {
            // 清除对应字段的错误提示
            if (this.formErrors[field]) {
                this.$set(this.formErrors, field, null);
            }
        },

        // 切换默认地址
        toggleDefault(e) {
            this.isDefault = e.detail.value;
        },

        // 选择标签
        selectTag(tag) {
            this.selectedTag = tag;
            // 如果选择自定义，可以弹出输入框让用户输入
            if (tag === '自定义') {
                uni.showInput({
                    title: '输入自定义标签',
                    success: (res) => {
                        if (res.value) {
                            this.selectedTag = res.value;
                        } else {
                            this.selectedTag = '';
                        }
                    }
                });
            }
        },

        // 切换地址粘贴板显示/隐藏
        togglePasteBoard() {
            this.showPasteBoard = !this.showPasteBoard;
        },

        // 获取地址粘贴板历史
        getPasteHistory() {
            // 实际项目中可以从本地存储或接口获取
            const history = uni.getStorageSync('addressPasteHistory') || [];
            this.pasteHistory = history;
        },

        // 使用粘贴板地址
        usePasteAddress(item) {
            this.receiverName = item.name;
            this.phoneNumber = item.phone;
            this.currentLocation = {
                name: item.locationName,
                area: item.area,
                longitude: item.longitude,
                latitude: item.latitude
            };
            this.houseNumber = item.houseNumber;
            this.selectedTag = item.tag || '';
            this.showPasteBoard = false;
        },

        // 选择地址（模拟地图选址）
        chooseLocation() {
            if (this.currentTab === 'map') {
                // 调用地图选择接口（实际项目中可使用uni.chooseLocation）
                uni.chooseLocation({
                    success: (res) => {
                        this.currentLocation = {
                            name: res.name,
                            area: res.address,
                            longitude: res.longitude,
                            latitude: res.latitude
                        };
                    }
                });
            } else {
                // 地区选择逻辑（可弹出地区选择器）
                uni.showToast({
                    title: '地区选择功能待实现',
                    icon: 'none'
                });
            }
        },
 

      
    // 确认选择地区
    confirmRegion() {
      console.log('选中的地区：', this.selectedRegion);
      this.showRegionPopup = false; // 关闭弹窗
    },
  
        // 加载地区数据（用于地区选址）
        loadRegionData() {
            // 实际项目中调用地区接口
            console.log('加载地区数据');
        },

        // 提交地址信息
        submitAddress() {
            // 表单验证
            if (!this.receiverName) {
                this.$set(this.formErrors, 'receiverName', '请填写收货人姓名');
                return;
            }

            if (!this.phoneNumber || !/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
                this.$set(this.formErrors, 'phoneNumber', '请填写正确的手机号');
                return;
            }

            if (!this.currentLocation.name) {
                uni.showToast({
                    title: '请选择地址',
                    icon: 'none'
                });
                return;
            }

            if (!this.houseNumber) {
                this.$set(this.formErrors, 'houseNumber', '请填写门牌号');
                return;
            }

            // 构造提交数据
            const addressData = {
                receiverName: this.receiverName,
                phoneNumber: this.phoneNumber,
                houseNumber: this.houseNumber,
                isDefault: this.isDefault,
                tag: this.selectedTag,
                locationName: this.currentLocation.name,
                area: this.currentLocation.area,
                longitude: this.currentLocation.longitude,
                latitude: this.currentLocation.latitude,
                // 接口需要的其他参数
                functionId: 'addr_add',
                appid: 'jd_mall',
                client: 'android'
            };

            // 调用接口提交地址
            uni.request({
                url: 'https://api.m.jd.com/client.action',
                method: 'POST',
                data: addressData,
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: (res) => {
                    console.log('地址提交结果:', res.data);
                    if (res.data.success) {
                        // 保存到粘贴板历史
                        this.saveToPasteHistory(addressData);

                        uni.showToast({
                            title: '地址添加成功',
                            icon: 'success'
                        });

                        // 返回上一页
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: res.data.msg || '添加失败，请重试',
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    console.error('地址提交失败:', err);
                    uni.showToast({
                        title: '网络错误，请重试',
                        icon: 'none'
                    });
                }
            });
        },

        // 保存到地址粘贴板
        saveToPasteHistory(addressData) {
            const newItem = {
                name: addressData.receiverName,
                phone: addressData.phoneNumber,
                locationName: addressData.locationName,
                area: addressData.area,
                houseNumber: addressData.houseNumber,
                tag: addressData.tag,
                longitude: addressData.longitude,
                latitude: addressData.latitude,
                createTime: new Date().getTime()
            };

            // 限制历史记录数量
            this.pasteHistory.unshift(newItem);
            if (this.pasteHistory.length > 10) {
                this.pasteHistory.pop();
            }

            // 保存到本地存储
            uni.setStorageSync('addressPasteHistory', this.pasteHistory);
        }
    }
};
</script>

<style scoped>
.add-address-page {
    padding: 20rpx;
}

.form-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 30rpx;
}

.label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
}

.input {
    height: 80rpx;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
}

.input.error {
    border-color: #ff4d4f;
}

.error-tip {
    font-size: 24rpx;
    color: #ff4d4f;
    margin-top: 5rpx;
}

.address-section {
    margin-bottom: 30rpx;
}

.tab-bar {
    display: flex;
    border-bottom: 1rpx solid #ddd;
    margin-bottom: 20rpx;
}

.tab {
    padding: 20rpx 30rpx;
    font-size: 28rpx;
    position: relative;
    bottom: -1rpx;
}

.tab.active {
    color: #ff5454;
    border-bottom: 4rpx solid #ff5454;
}

.address-select {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
}

.current-location {
    font-size: 28rpx;
}

.location-desc {
    font-size: 24rpx;
    color: #999;
    margin-top: 6rpx;
}

.use-btn {
    width: 120rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 26rpx;
    border: 1rpx solid #333;
    border-radius: 6rpx;
}

.paste-board {
    text-align: center;
    font-size: 26rpx;
    color: #666;
    margin: 10rpx 0;
    padding: 10rpx;
}

.paste-content {
    border: 1rpx solid #eee;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
}

.paste-item {
    padding: 15rpx;
    border-bottom: 1rpx solid #eee;
    font-size: 26rpx;
}

.paste-item:last-child {
    border-bottom: none;
}

.tip {
    font-size: 24rpx;
    color: #999;
    margin-top: 6rpx;
}

.tag-group {
    display: flex;
    flex-wrap: wrap;
}

.tag {
    padding: 14rpx 28rpx;
    margin: 0 10rpx 16rpx 0;
    border: 1rpx solid #ddd;
    border-radius: 30rpx;
    font-size: 26rpx;
}

.tag.active {
    background-color: #ff5454;
    color: #fff;
    border-color: #ff5454;
}

.tag.custom {
    color: #ff5454;
    border-color: #ff5454;
}

.confirm-btn {
    width: 100%;
    height: 90rpx;
    background-color: #ff5454;
    color: #fff;
    font-size: 32rpx;
    border-radius: 10rpx;
}

.confirm-btn:disabled {
    background-color: #ccc;
}
</style>